from pygo1963.model.Constants import WHITE_COLOR
from pygo1963.model.Move import Move
from pygo1963.model.Vertex import Vertex
import os.path

class OpeningKnowledge(object):
    """
    Class with access to the opening data base.
    """


    def __init__(self, color):
        """
        Opening Knowledge 
        """
        
        self.color = "white" if color == WHITE_COLOR else "black"
        self.board_size = None
        self.database = None
    
    def _init(self):
        """
        Initialization of the opening knowledge.
        """
        
        try:
            ART_PATH = os.path.join(os.path.dirname( __file__ ), '../../../openings/')
            file_name = 'openings.%s.%d.go' % (self.color, self.board_size)
            file = open(ART_PATH + file_name, 'r')
            self.database = eval(file.read())
        except IOError:
            self.database = None
    
    def get_opening_move(self, board):
        """
        Return the move according to the board.
        """
        
        if board.size != self.board_size:
            self.board_size = board.size
            self._init()
        
        board_as_string = board.as_string()
        
        if self.database and self.database.has_key(board_as_string):
            color, vertex = self.database[board_as_string].split()
            return Move(color, Vertex.from_string(vertex))